package com.xingongchang.baolebei.activity;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.external.androidquery.callback.AjaxStatus;
import com.insthub.BeeFramework.activity.BaseActivity;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.ToastView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.fragment.BitmapUtils;
import com.xingongchang.baolebei.model.ProtocolConst;
import com.xingongchang.baolebei.model.UserInfoModel;
import com.xingongchang.baolebei.photo.Bimp;
import com.xingongchang.baolebei.photo.FileUtils;
import com.xingongchang.baolebei.photo.PhotoActivity;

public class Update_Topic extends  BaseActivity implements BusinessResponse {
	public final int TEXT_MAX = 5000;
	private EditText updatetopic_body,updatetopic_title;
	private LinearLayout update_line;
	ImageLoader imageLoader = ImageLoader.getInstance();
	JSONArray jsonarray = new JSONArray();
	String imgid="";
	ProgressDialog pd;
	boolean booleans=false;
	private ImageView update_back;
	private GridView photos;
	private GridAdapter adapter;
	String topicTitle ;
	String topicBody ;
	private UserInfoModel mUserInfoModel;
	int topicid;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.updatetopic);
		topicid=getIntent().getIntExtra("topic", 0);
		intiview();
		//限制字数
		benlane();
		setListener();
		init();
	}
	private void setListener() {
		update_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Bimp.bmp.clear();
				Bimp.drr.clear();
				Bimp.imgId.clear();
				Bimp.max = 0;
				FileUtils.deleteDir();
				finish();
			}
		});
		update_line.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				processThread();
			}
		});
	}
	private void benlane() {
		// 输入框限制输入字数
		updatetopic_body.addTextChangedListener(new TextWatcher() {
					private CharSequence temp;
					private int selectionStart;
					private int selectionEnd;

					@Override
					public void beforeTextChanged(CharSequence s, int arg1, int arg2,
							int arg3) {
						temp = s;
					}

					@Override
					public void onTextChanged(CharSequence s, int arg1, int arg2,
							int arg3) {
					}

					@Override
					public void afterTextChanged(Editable s) {
						selectionStart =updatetopic_body.getSelectionStart();
						selectionEnd =updatetopic_body.getSelectionEnd();
						if (temp.length() > TEXT_MAX) {
							Toast.makeText(Update_Topic.this, "文字不能超出5000字",
									Toast.LENGTH_SHORT).show();
							s.delete(selectionStart - 1, selectionEnd);
							int tempSelection = selectionStart;
							updatetopic_body.setText(s);
							updatetopic_body.setSelection(tempSelection);
						}
					}

				});
	}
	private void intiview() {
		updatetopic_body=(EditText) findViewById(R.id.updatetopic_body);//内容
		updatetopic_title=(EditText) findViewById(R.id.updatetopic_title);//标题
		update_line=(LinearLayout) findViewById(R.id.update_line);//更新
		update_back=(ImageView) findViewById(R.id.update_back);//返回
	}
	protected void processThread() {
		// TODO Auto-generated method stub
		// 构建一个下载进度条
		pd = ProgressDialog.show(Update_Topic.this, "上传图片", "数据处理中...");
		new Thread() {
			@Override
			public void run() {

				// 在新线程里执行长耗时方法
				try {
					longTimeMethod();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				// 执行完毕后给handler发送一个空消息
				handler.sendEmptyMessage(0);
			}
		}.start();
	}
	private Handler handler = new Handler() {
		// 当有消息发送出来的时候就执行Handler的这个方法
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			// 只要执行到这里就关闭对话框
			pd.dismiss();
//			pic = jsonarray.toString();
			topicTitle = updatetopic_title.getText().toString().trim();
			topicBody = updatetopic_body.getText().toString().trim();
			if (topicTitle.equals("")) {
				Toast.makeText(Update_Topic.this, "标题不能为空",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (topicBody.equals("")) {
				Toast.makeText(Update_Topic.this, "帖子内容不能为空",
						Toast.LENGTH_SHORT).show();
				return;
			}
			    	mUserInfoModel.UpdateDatails(topicid, topicTitle, topicBody, jsonarray,imgid);
				
		}

	};
	// 执行长耗时方法
		protected void longTimeMethod() throws JSONException {
//			int count = 0;
			imgid="";
			jsonarray = new JSONArray();
			for(int i=0;i<Bimp.bmp.size();i++){
				Bimp.imgId.remove((Integer)0);
				if(i<Bimp.imgId.size()){
					JSONObject jsonObj = new JSONObject();
						Log.e("u2nimgid",Bimp.imgId.toString());
//						jsonObj.put("id", Bimp.imgId.get(i));
						imgid +=Bimp.imgId.get(i)+",";
//						jsonarray.put(jsonObj);						
				}else{
					Bitmap bm = Bimp.bmp.get(i);
					JSONObject jsonObj = new JSONObject();
					String img = imgToBase64("", bm, "");
					try {
						jsonObj.put("img", img);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					jsonarray.put(jsonObj);
					
				}
				
			}
//			for (int i = 0; i < Bimp.bmp.size(); i++) {
//				Bitmap bm = Bimp.bmp.get(i);
//				String img = imgToBase64("", bm, "");
//				if(!img.equals("")){
//					try {
//						JSONObject jsonObj = new JSONObject();
//                 		jsonObj.put("img", img);
////						jsonObj.put("newImg", img);
//						jsonarray.put(jsonObj);
//						count ++ ;
//					} catch (JSONException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					if(count == Bimp.bmp.size()){
//						return;
//					}
//				}
//			
//				
//			}
//				Thread.sleep(10000);
		}

		private void init() {
			photos = (GridView) findViewById(R.id.updatephotoGridview);
			photos.setSelector(new ColorDrawable(Color.TRANSPARENT));
			adapter = new GridAdapter(Update_Topic.this);
			adapter.update();
			photos.setAdapter(adapter);
			photos.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					if (position == Bimp.bmp.size()) {
						dialogNote();
					} else {
						Intent intent = new Intent(Update_Topic.this,
								PhotoActivity.class);
						intent.putExtra("ID", position);
						startActivity(intent);
					}
				}
			});
			mUserInfoModel = new UserInfoModel(this);
		    mUserInfoModel.getTopicDetails(topicid);
			mUserInfoModel.addResponseListener(this);
		}

		public class GridAdapter extends BaseAdapter {

			private LayoutInflater inflater; // 视图容器
			private int selectedPosition = -1;// 选中的位置
			private boolean shape;

			public boolean isShape() {
				return shape;
			}

			public void setShape(boolean shape) {
				this.shape = shape;
			}

			public GridAdapter(Context context) {
				inflater = LayoutInflater.from(context);
			}

			public void update() {
				loading();
			}

			public int getCount() {
				return (Bimp.bmp.size() + 1);
			}

			public Object getItem(int arg0) {

				return null;
			}

			public long getItemId(int arg0) {

				return 0;
			}

			public void setSelectedPosition(int position) {
				selectedPosition = position;
			}

			public int getSelectedPosition() {
				return selectedPosition;
			}

			/**
			 * ListView Item设置
			 */
			public View getView(int position, View convertView, ViewGroup parent) {

				ViewHolder holder = null;
				if (convertView == null) {

					convertView = inflater.inflate(R.layout.album_item, parent,
							false);
					holder = new ViewHolder();
					holder.image = (ImageView) convertView
							.findViewById(R.id.item_grida_image);
					convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}

				if (position == Bimp.bmp.size()) {
					holder.image.setImageBitmap(BitmapFactory.decodeResource(
							getResources(), R.drawable.btn_addpic));
					if (position == 8) {
						holder.image.setVisibility(View.GONE);
					}
				} else {
//					TOPIC_DETAIL detail=mUserInfoModel.topicDetail;
//					imageLoader.displayImage(detail.imgurl[position], holder.image);
					holder.image.setImageBitmap(Bimp.bmp.get(position));
				}

				return convertView;
			}

			public class ViewHolder {
				public ImageView image;
			}

			Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case 1:
						adapter.notifyDataSetChanged();
						break;
					}
					super.handleMessage(msg);
				}
			};

			public void loading() {
				new Thread(new Runnable() {
					public void run() {

						while (true) {
							if (Bimp.max == Bimp.drr.size()) {
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
								break;
							} else {
								try {
									if (Bimp.drr.get(Bimp.max).startsWith("http")) {
										String path = Bimp.drr.get(Bimp.max);
										Bitmap bm = BitmapUtils.returnBitMap(path);
										Bimp.bmp.add(bm);
										String newStr = path.substring(
												path.lastIndexOf("/") + 1,
												path.lastIndexOf("."));
										FileUtils.saveBitmap(bm, "" + newStr);
//										if(Bimp.max == Bimp.drr.size() - 1){
//										}
									} else {
									String path = Bimp.drr.get(Bimp.max);
									Bitmap bm = Bimp.revitionImageSize(path);
									Bimp.bmp.add(bm);
									String newStr = path.substring(
											path.lastIndexOf("/") + 1,
											path.lastIndexOf("."));
									FileUtils.saveBitmap(bm, "" + newStr);
									
									}
								} catch (IOException e) {

									e.printStackTrace();
								}
								Bimp.max += 1;
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
							}
						}
					}
				}).start();
			}
		}

		protected void onRestart() {
			adapter.update();
			super.onRestart();
		}

		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);

			if (requestCode == PHOTO_REQUEST_CAREMA) {
				// 从相机返回的数据
//				if (data != null) {
					// Bitmap bitmap = data.getParcelableExtra("data");
				String path = Environment.getExternalStorageDirectory() + "/"
						+ PHOTO_FILE_NAME;
				Bimp.drr.add(path);
//				}
				// if (hasSdcard()) {
				// crop(Uri.fromFile(tempFile));
				// } else {
				// Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT)
				// .show();
				// }
			} else if (requestCode == PHOTO_REQUEST_CUT) {
				// 从剪切图片返回的数据
				// if (data != null) {
				// // Bitmap bitmap = data.getParcelableExtra("data");
				// Bimp.drr.add(Environment.getExternalStorageDirectory() + "/"
				// + PHOTO_FILE_NAME);
				// }
				// try {
				// // 将临时文件删除
				// tempFile.delete();
				// } catch (Exception e) {
				// e.printStackTrace();
				// }

			}
		}
	
	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		if (url.endsWith(ProtocolConst.UPDATE_TOPIC)) {
			if(mUserInfoModel.responseStatus.succeed==1){
				booleans=true;
				  if(booleans==true){
						ToastView toast = new ToastView(Update_Topic.this, "帖子修改成功");
				        toast.setGravity(Gravity.CENTER, 0, 0);
				        toast.show();
				        Intent intent=new Intent(Update_Topic.this,BaolebeiActivity.class);
				        startActivity(intent);
					}
					Bimp.bmp.clear();
					Bimp.drr.clear();
					Bimp.max = 0;
					FileUtils.deleteDir();
					finish();
			}
		}else if (url.endsWith(ProtocolConst.TOPIC_DETAIL)) {
			if(mUserInfoModel.responseStatus.succeed==1){
				updatetopic_title.setText(mUserInfoModel.topicDetail.title);
				updatetopic_body.setText(mUserInfoModel.topicDetail.body);
				Bimp.bmp.clear();
				Bimp.drr.clear();
				Bimp.imgId.clear();
				Bimp.max = 0;
				for(int i=0;i<mUserInfoModel.topicDetail.imgurl.length;i++){
					
					Bimp.drr.add(mUserInfoModel.topicDetail.imgurl[i]);
					Bimp.imgId.add(mUserInfoModel.topicDetail.imgId[i]);
					Log.d("api",mUserInfoModel.topicDetail.imgurl[i]);
				}
				adapter.update();
			}
		}
	}

}
